﻿using System;
using System.Data;
using System.Data.Common;

namespace Dataglot
{
    public class TransactionManager:IDisposable
    {
        private readonly DbConnection con;
        private bool isCommitted;
        public DbTransaction Transaction { get; private set; }

        public TransactionManager(DbConnection dbConnection)
        {
            con = dbConnection;
        }

        public void Begin()
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            Transaction= con.BeginTransaction();
        }

        public void Begin(IsolationLevel level)
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            Transaction = con.BeginTransaction(level);
        }

        public void Commit()
        {
            isCommitted = true;
            if(Transaction!=null)
                Transaction.Commit(); 
        }

        public void Dispose()
        {
            if (!isCommitted)
            {
                if (Transaction != null)
                {
                    try
                    {
                        Transaction.Rollback();
                    }
                    finally     
                    {
                        Transaction.Dispose();
                    }
                }
            }
            else
            {
                if (Transaction != null)
                {
                    Transaction.Dispose();
                }
            }

            //if (chartCommand != null)
            //    chartCommand.Dispose();

            if (con != null)
            {
                if (con.State == ConnectionState.Open)
                    con.Close();
                con.Dispose();
            }

        }
    }

}
